@echo off
setlocal enabledelayedexpansion
chcp 65001 > nul

set "JAR_PATH=%~dp0tray-manager.jar"
set "ICON_PATH=%~dp0icon.ico"
set "WINDOW_TITLE=ScanOS Control"
set "LOG_FILE=%~dp0tray-output.log"

if not exist "%JAR_PATH%" (
    echo 错误: 未找到 tray-manager.jar
    pause
    exit /b 1
)

if not exist "%ICON_PATH%" (
    set "ICON_PATH=%~dp0icon.png"
)

rem 优先使用注册表中指定的Java路径
set "JAVA_CMD="
for /f "tokens=2,*" %%a in ('reg query "HKLM\SOFTWARE\ScanOS" /v JavaHome 2^>nul') do (
    set "java_home=%%b"
)

if defined java_home (
    set "java_cmd=!java_home!\bin\javaw.exe"
    if exist "!java_cmd!" (
        set "JAVA_CMD="!java_cmd!""
        goto :found_java
    )
)

rem 查找合适的Java (使用where命令)
for /f "delims=" %%j in ('where javaw 2^>nul') do (
    if "!JAVA_CMD!"=="" (
        set "JAVA_CMD="%%j""
    )
)

if "!JAVA_CMD!"=="" (
    for /f "delims=" %%j in ('where java 2^>nul') do (
        if "!JAVA_CMD!"=="" (
            set "JAVA_CMD="%%j""
        )
    )
)

:found_java
if "!JAVA_CMD!"=="" (
    echo 错误: 未找到Java运行时
    pause
    exit /b 1
)

rem 添加兼容性参数 (确保所有路径正确引用)
set "CMD=!JAVA_CMD! -Dsun.java2d.uiScale=1.0 -Dsun.awt.noerasebackground=true -Dsun.awt.window.title="!WINDOW_TITLE!" -jar "%JAR_PATH%""
if exist "!ICON_PATH!" (
    set "CMD=!CMD! --tray-icon="!ICON_PATH!""
)

rem 启动程序并记录输出
start "" /B cmd /c "!CMD!" > "!LOG_FILE!" 2>&1

rem 添加延迟确保进程启动
timeout /t 3 /nobreak >nul

exit /b 0